package com.yonyou.pmclouds.enterprise.process;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.dao.dialect.H2Dialect;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseQueryParam;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.mapper.EnterpriseMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author chulf
 * @Date 2020/4/15
 * @Description 企业名字唯一校验
 **/
public class NameUniqueCheckBeforeProcess implements SingleProcessor<EnterpriseVO>, MultiProcessor<EnterpriseVO> {

    private EnterpriseMapper mapper;
    public NameUniqueCheckBeforeProcess(EnterpriseMapper mapper){
        this.mapper = mapper;
    }

    @Override
    public void process(EnterpriseVO vo, EnterpriseVO orig) throws BusinessException {

        if (orig != null) {
            if (vo.getName().equalsIgnoreCase(orig.getName())) return;
        }

        checkName(new EnterpriseVO[]{vo});

    }

    @Override
    public void process(EnterpriseVO[] vos, EnterpriseVO[] origs) throws BusinessException {
        if(vos == null || vos.length <= 0){
            return;
        }

        checkName(vos);
    }

    private void checkName(EnterpriseVO[] vos) throws BusinessException {
        EnterpriseQueryParam enterpriseQueryParam = new EnterpriseQueryParam();
        enterpriseQueryParam.setTenantId(RuntimeEnvironment.getTenantId());
        EnterpriseVO[] enterpriseVOS = mapper.selectEtpsByCondition(enterpriseQueryParam);

        Map<String, EnterpriseVO> enterpriseVOMap = new HashMap<>();
        for (EnterpriseVO enterpriseVO : enterpriseVOS) {
            enterpriseVOMap.put(enterpriseVO.getName(), enterpriseVO);
        }

        for(EnterpriseVO enterpriseVO : vos){
            if(enterpriseVOMap.containsKey(enterpriseVO.getName())){
                throw new BusinessException("企业名称:[" + enterpriseVO.getName() + "]已存在请修改!");
            }
        }

    }
}